<template>
    <div class="box">
        <header>
            <van-nav-bar title="购物车" left-text="返回" left-arrow @click-left="$router.back()" />
        </header>
        <div class="content">
            <van-empty description="购物车空空如也" v-if="cartList.length == 0" />
            <van-swipe-cell v-else v-for="item in cartList" :key="item.id">
                <van-card :num="item.count" :price="`${item.price}.00`" :title="item.title" class="goods-card"
                    :thumb="item.image">
                    <template #tag>
                        <van-checkbox v-model="item.checked" @change="onChange"></van-checkbox>
                    </template>
                    <template #footer>
                        <van-stepper v-model="item.count" min="1" max="10" @change="onChange" />
                    </template>
                </van-card>
                <template #right>
                    <van-button square text="删除" type="danger" class="delete-button" @click="deleteItem(item.id)" />
                </template>
            </van-swipe-cell>
        </div>

    </div>
    <footer class="footer">
        <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="$router.push('/order')">
            <van-checkbox v-model="allChecked">全选</van-checkbox>
        </van-submit-bar>
    </footer>
</template>
<script>
import { mapState, mapMutations, mapGetters } from 'vuex'
export default {
    computed: {
        ...mapState(['cartList']),
        ...mapGetters(['totalPrice']),
        allChecked: {
            get() {
                // 获取 全选按钮的值 全选按钮是否要被勾上
                if (this.cartList.length == 0) {
                    return false
                } else {
                    return this.cartList.every(item => item.checked)
                }
            },
            set(newval) {
                // 全选按钮被勾上的时候，要将cartList中每个item的checked都设置为true,
                // 全选按钮没有被勾上时，要将cartList中每个item的checked都设置为false
                // this.cartList.forEach(item => item.checked = newval)
                this.changecheck(newval)
            }
        },
    },
    methods: {
        ...mapMutations(['changecheck', 'deleteCart', 'updatecartList']),
        deleteItem(id) {
            // 去cartList找到id相同的那条删除掉
            // 只能在mutations中修改公共数据
            this.deleteCart(id)
        },
        onChange() {
            console.log(this.cartList, 'cartList')
            this.updatecartList(this.cartList)
        }
    },
}
</script>

<style lang="scss" scoped>
.delete-button {
    height: 100%;
}

.van-swipe-cell {
    margin-bottom: 10px;
}
</style>